package slideWindows;

import java.util.Deque;
import java.util.LinkedList;

/**
 * @author le
 */
public class TheMaxArraySlideWindow {

    /**
     * 239. 滑动窗口最大值
     * 给你一个整数数组 nums，有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口内的 k 个数字。滑动窗口每次只向右移动一位。
     *
     * 返回滑动窗口中的最大值。
     * @param args
     */

    public static void main(String[] args) {
        int[] nums = {1,3,-1,-3,5,3,6,7};
        int k = 3;
        int index = 0;
        int[] res = new int[nums.length-k+1];
        for (int i = 0;i < nums.length-k+1;i++){
            for (int j = i;j < i+k;j++){
                if (nums[i] < nums[j]){
                    nums[i] = nums[j];
                }
            }
            res[index] = nums[i];
            index++;

        }

        for (int i = 0; i < res.length; i++) {
            System.out.println(res[i]);
        }

    }

    /**
     * 官方题解
     */

    public int[] maxSlidingWindow(int[] nums, int k) {
        int n = nums.length;
        Deque<Integer> deque = new LinkedList<Integer>();
        for (int i = 0; i < k; ++i) {
            while (!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]) {
                deque.pollLast();
            }
            deque.offerLast(i);
        }

        int[] ans = new int[n - k + 1];
        ans[0] = nums[deque.peekFirst()];
        for (int i = k; i < n; ++i) {
            while (!deque.isEmpty() && nums[i] >= nums[deque.peekLast()]) {
                deque.pollLast();
            }
            deque.offerLast(i);
            while (deque.peekFirst() <= i - k) {
                deque.pollFirst();
            }
            ans[i - k + 1] = nums[deque.peekFirst()];
        }
        return ans;
    }
}
